package com.ayu.a.practice02;

import java.util.Arrays;

/**
 * @Author 徐林玉
 * @Description LongestCommonPrefixPrac
 * @Date 2022/11/15 16:14
 * @Version 1.0
 */
public class LongestCommonPrefixPrac {

    public static void main(String[] args) {

        String[] strs = new String[]{"cir","car"};

        String s = longestCommonPrefix(strs);

        System.out.println("s = " + s);


    }

    public static String longestCommonPrefix(String[] strs){

        char[] orin = strs[0].toCharArray();

        int[] clt = new int[strs.length];

        int index = -1;

        for (int i = 1; i < strs.length; i++) {

            char[] c = strs[i].toCharArray();



            for (int j = 0; j < (c.length<=orin.length?c.length:orin.length); j++) {

                if(c[j] == orin[j]){

                    index = j;
                }else{
                    break;
                }
            }

            clt[i] = index;

            index = - 1;
        }
        clt[0] = orin.length-1;


        Arrays.sort(clt);

        String s = "";

        if(clt[0]!=-1){

            char[] chars = Arrays.copyOfRange(orin, 0, clt[0]+1);

            s = String.valueOf(chars);
        }

        return s;


    }
}
